<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>权限管理</title>
    <script src="../js/vue3.js"></script>
    <script src="../js/axios-0.18.0.js"></script>
    <script src="../js/element-plus.js"></script>
    <script src="../js/icons-vue.js"></script>
    <script src="../js/zh-cn.js"></script>
    <link rel="stylesheet" href="../css/index.css"/>
</head>
<body>
<div id="app">
<!--    上传组件-->
    <div>
        <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                action="/permission/upload"
                multiple
                :limit="3"
                :on-success="onSuccess"
        >
            <el-button type="primary">上传文件</el-button>
            <template #tip>
                <div class="el-upload__tip">
                    jpg/png files with a size less than 500KB.
                </div>
            </template>
        </el-upload>
    </div>

    <el-button type="success" @click="download">下载文件模板</el-button>
    <div>
        <el-table :data="filterTableData" style="width: 100%">
            <el-table-column label="编号" prop="id"></el-table-column>
            <el-table-column label="父ID" prop="pname"></el-table-column>
            <el-table-column label="权限名称" prop="parentId"></el-table-column>
            <el-table-column label="URL" prop="url"></el-table-column>
            <el-table-column label="权限编码" prop="code"></el-table-column>
            <el-table-column label="权限等级" prop="level"></el-table-column>
            <el-table-column label="排序" prop="sort"></el-table-column>
            <el-table-column align="right">

                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)"
                    >编辑
                    </el-button
                    >
                    <el-button
                            size="small"
                            type="danger"
                            @click="handleDelete(scope.row)"
                    >删除
                    </el-button
                    >
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!--    //分页-->
    <div>
        <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[4, 6, 8, 10]"
                :small="small"
                :disabled="disabled"
                :background="background"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"></el-pagination>
    </div>
    <div>
        <el-dialog
                v-model="dialogVisible"
                title="编辑权限信息"
                width="600px"
                :before-close="handleClose"
        >
            <el-form
                    ref="ruleFormRef"
                    :model="form"
                    :rules="rules"
                    label-width="120px"
                    status-icon
            >
                <el-form-item label="权限名称" prop="pname">
                    <el-input v-model="form.pname" placeholder="请输入权限名称"></el-input>
                </el-form-item>
                <el-form-item label="URL地址" prop="url">
                    <el-input v-model="form.url" placeholder="请输入URL地址"></el-input>
                </el-form-item>
                <el-form-item label="权限代码" prop="code">
                    <el-input v-model="form.code" placeholder="请输入权限代码"></el-input>
                </el-form-item>
                <el-form-item label="权限级别" prop="level">
                    <el-input v-model="form.level" placeholder="请输入权限代码权限级别"></el-input>
                </el-form-item>
                <el-form-item label="排序号" prop="sort">
                    <el-input-number v-model="form.sort" :min="1" :max="100"></el-input-number>
                </el-form-item>
            </el-form>
            <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitForm">保存</el-button>
                    </span>
            </template>
        </el-dialog>
    </div>
</div>

<script>
    const {createApp, ref, computed, onMounted, nextTick} = Vue;
    const {ElMessage, ElMessageBox} = ElementPlus;
    createApp({
        setup() {
            // 获取数据
            const filterTableData = ref([])
            const total = ref(1)
            const currentPage = ref(1)
            const pageSize = ref(4)
            const handleSizeChange = (val) => {
                pageSize.value = val;
                getAllPerms();
            }
            const handleCurrentChange = (val) => {
                currentPage.value = val;
                getAllPerms();
            }
            const getAllPerms = () => {
                axios.get(`/permission/${currentPage.value}/${pageSize.value}`).then(resp => {
                    //将返回searchQuery.value回来的集合数据赋值给表格绑定的数据源变量
                    //   resp.data   Result(obj:自己的集合数据)
                    console.log(resp.data)
                    filterTableData.value = resp.data.data.list;
                    total.value = resp.data.data.total;
                })
            }
            onMounted(() => {
                // 模拟API调用延迟
                getAllPerms();
            });
            // 删除数据
            const handleDelete = (row) => {
                ElMessageBox.confirm(`确定要删除用户吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',

                }).then(() => {
                    // let mid = row.buildingId;
                    axios.delete(`/permission/${row.id}`).then(resp => {
                        if (resp.data.code === 200) {
                            ElMessage.success(resp.data.msg);
                            getAllPerms();
                        } else {
                            alert("删除失败")
                        }
                    }).catch(error => {
                        ElMessage.error(error.response.data.msg);
                    })
                })
                    .catch(() => {
                        ElMessage({
                            type: 'info',
                            message: '取消删除',
                        })
                    })
            }
//编辑数据

            const form = ref([])
            const dialogVisible = ref(false)
            const title = ref("修改用户")
            const handleEdit = (row) => {
                axios.get(`/permission/getById/${row.id}`)
                    .then(resp => {
                        console.log(resp.data)
                        form.value = resp.data.data;
                        dialogVisible.value = true; // 显示弹窗
                        title.value = ref("修改业主")
                    })
                    .catch(error => {
                        ElMessage.error(error.response.data.msg);
                    })
            }
            const submitForm = () => {
                updatePermission();
            }

            const updatePermission = () => {
                axios.put("/permission", form.value).then(resp => {
                    // 判断resp.data 是否大于1，如果大于1 则修改成功，刷新页面，关闭弹窗
                    if (resp.data.code === 200) {
                        data(resp.data.msg);
                    } else {
                        ElMessage.error(error.response.data.msg)
                    }
                })
            }
            const data = (msg) => {
                ElMessage.success(msg);
                getAllPerms();
                form.value = {}
                dialogVisible.value = false
            }
            const fileList=ref([])
            // const onSuccess=(resp)=>{
            //     ElMessage.success(resp.msg);
            //     fileList.value=[]
            // }

            // const beforeUpload= (rawFile) => {
            //     // 正确的Excel文件MIME类型检查
            //     const allowedTypes = [
            //         'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
            //         'application/vnd.ms-excel' // .xls
            //     ];
            //
            //     if (!allowedTypes.includes(rawFile.type)) {
            //         ElMessage.error('您上传的文件必须是Excel格式（.xlsx或.xls）')
            //         return false
            //     } else if (rawFile.size / 1024 / 1024 > 2) {
            //         ElMessage.error('您的文件最大不能超过2MB!')
            //         return false
            //     }
            //     return true
            // }
            const download=()=>{
                window.location.href="/permission/downloadModel/perms -model.xlsx"
            }
            const getPermModel = async (fileName) => {
                fileName = "perms-model.xlsx";
                try {
                    const response = await fetch("/permission/downloadModel/perms-model.xlsx", {
                        method: 'GET',
                    });

                    console.log(JSON.stringify(response))

                    if (response.ok) {
                        // 获取自定义响应头
                        const message = response.headers.get('X-Download-Message') || '下载成功';
                        const filename = response.headers.get('X-Download-Filename') || fileName;

                        // 创建下载链接
                        const blob = await response.blob();
                        const url = window.URL.createObjectURL(blob);
                        const link = document.createElement('a');
                        link.href = url;
                        link.download = filename;
                        document.body.appendChild(link);
                        link.click();
                        link.remove();
                        window.URL.revokeObjectURL(url);

                        ElMessage.success(message);
                    } else {
                        const errorData = await response.json();
                        ElMessage.error(errorData.message || '下载失败');
                    }
                } catch (error) {
                    ElMessage.error('下载失败: ' + error.message);
                }
            };
            return {
                filterTableData, getAllPerms, total, currentPage, pageSize, handleSizeChange, handleCurrentChange,
                handleDelete, form, dialogVisible, title, handleEdit, submitForm, updatePermission,fileList,
                download

            }
        }
    }).use(ElementPlus, {
        locale: ElementPlusLocaleZhCn
    }).mount('#app');
</script>
</body>
</html>